import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:myapp/common_ui/web/webview_page.dart';
import 'package:myapp/common_ui/web/webview_widget.dart';
import 'package:myapp/pages/home/home_vm.dart';
import 'package:myapp/route/route_utils.dart';
import 'package:myapp/route/routes.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../common_ui/loading.dart';
import '../../common_ui/smart_refresh/smart_refresh_widget.dart';
import '../../repository/datas/home_list_data.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    Loading.showLoading();
    viewModel.getBanner();
    refreshOrLoad(false);
  }

  void refreshOrLoad(bool loadMore){
    viewModel.initListData(loadMore,callback: (loadMore){
      if(loadMore){
        refreshController.loadComplete();
      }else{
        refreshController.refreshCompleted();
      }
      //close loading
      Loading.dismissAll();
    });
  }

  @override
  Widget build(BuildContext context) {
    ///Scaffold 页面的脚手架
    return ChangeNotifierProvider<HomeViewModel>(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        //SafeArea 安全区域,不包含app bar 和bottom  的区域
        body: SafeArea(
          child: SmartRefreshWidget(
            controller: refreshController,
            onLoading: (){
              //上拉加载回调
              viewModel.initListData(true,callback: (loadMore){
                refreshOrLoad(true);
              });
            },
            onRefresh: (){
              //下拉刷新回调
              viewModel.getBanner().then((value){
                refreshOrLoad(false);
              });
            },
            child: SingleChildScrollView(
              child: Column(children: [_banner(), _homeListView()]),
            ),
          ),
        ),
      ),
    );
  }

  Widget _homeListView() {
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return ListView.builder(
          shrinkWrap: true, //是否滚动视图在滚动方向上由内容的总尺寸决定大小
          physics: NeverScrollableScrollPhysics(), //禁用listView 的Scroll 特性
          itemBuilder: (context, index) {
            return _listItemView(vm.listItemData?[index],index);
          },
          itemCount: vm.listItemData?.length ?? 0,
        );
      },
    );
  }

  ///封装_banner
  Widget _banner() {
    print("_banner init");
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return Container(
          ///各种widget的容器，能设置各种属性
          height: 150.h,
          width: double.infinity,
          child: Swiper(
            indicatorLayout: PageIndicatorLayout.NONE,
            autoplay: true,
            pagination: const SwiperPagination(),
            control: const SwiperControl(),
            itemCount: vm.bannerList?.length ?? 0,
            itemBuilder: (context, index) {
              return GestureDetector(onTap: (){
                var bannerData = vm.bannerList?[index];
                RouteUtils.push(context, WebViewPage(loadResource: bannerData?.url ?? "",
                  webViewType: WebViewType.URL,title:bannerData?.title ?? "",showTitle: true,));
              },child: Container(
                height: 150.h,
                color: Colors.lightBlue,
                child: Image.network(
                  vm.bannerList?[index].imagePath ?? "",
                  fit: BoxFit.fill,
                ),
              ));
            },
          ),
        );
      },
    );
  }

  Widget _listItemView(HomeListItemData? item,int index) {
    String name;
    if (item?.author?.isNotEmpty == true) {
      name = item?.author ?? "";
    } else {
      name = item?.shareUser ?? "";
    }
    return GestureDetector(
      //InkWell() 水波纹效果
      onTap: () {
        //跳转到网页
        RouteUtils.push(context, WebViewPage(loadResource: item?.link??"", webViewType: WebViewType.URL
          ,title: item?.title ??"",showTitle: true,));
        // RouteUtils.pushForNamed(context,RoutePath.webViewPage,arguments: {"name": "参数传递过来的值"},);
        // Navigator.pushNamed(context, RoutePath.webViewPage);
        ///导航器
        // Navigator.push(context,MaterialPageRoute(builder: (context){
        //   return WebViewPage(title: "首页跳转来的");
        // }));
      },
      child: Container(
        margin: EdgeInsets.only(top: 5.h, bottom: 5.h, left: 10.w, right: 10.w),
        //设置边距
        padding: EdgeInsets.only(
          top: 15.h,
          bottom: 15.h,
          left: 10.w,
          right: 10.w,
        ),
        decoration: BoxDecoration(
          //容器设置装饰
          border: Border.all(color: Colors.black12, width: 0.5.r),
          borderRadius: BorderRadius.all(Radius.circular(6.r)), //圆角
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(15.r),
                  child: Image.network(
                    "https://tse1-mm.cn.bing.net/th/id/OIP-C.UWyuLdKb4fyJYdOjnvVoKwHaEG?pid=ImgDet&w=60&h=60&c=7&dpr=2&rs=1",
                    width: 30.r,
                    height: 30.r,
                    fit: BoxFit.fill,
                  ),
                ),
                SizedBox(width: 10.w),
                Text(name, style: TextStyle(color: Colors.black)),
                Expanded(child: SizedBox()),
                Text(
                  item?.niceShareDate ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 12.sp),
                ),
                SizedBox(width: 10.w),
                item?.type?.toInt() == 1
                    ? Text(
                        "置顶",
                        style: TextStyle(
                          color: Colors.blue,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                    : SizedBox(),
              ],
            ),
            SizedBox(height: 7.w),
            Text(
              item?.title ?? "",
              style: TextStyle(color: Colors.black, fontSize: 14.sp),
            ),
            SizedBox(height: 7.w),
            Row(
              children: [
                Text(
                  item?.chapterName ?? "",
                  style: TextStyle(color: Colors.green, fontSize: 14.sp),
                ),
                Expanded(child: SizedBox()),
                GestureDetector(onTap: (){
                  var isCollect;
                  if(item?.collect == true){
                    isCollect = false;
                  }else{
                    isCollect = true;
                  }
                  viewModel.collectOrNO(isCollect,"${item?.id}",index);
                },child: Image.asset(
                  item?.collect==true ? "assets/images/img_collect.png": "assets/images/img_collect_grey.png",
                  width: 30.w,
                  height: 30.h,
                )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
